//
//  AppDelegate.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/1/25.
//

#import "AppDelegate.h"
#import "IQKeyboardManager.h"
#import <AdSupport/AdSupport.h>
#import "SALoginVC.h"
#import <UMCommon/UMCommon.h>
#import <UMCommonLog/UMCommonLogHeaders.h>
#import <UMCommon/MobClick.h>
#import <UMCommonLog/UMCommonLogHeaders.h>
#import <UMPush/UMessage.h>
#import <UserNotifications/UserNotifications.h>
#import "CloudPrint.h"
#import <AipOcrSdk/AipOcrSdk.h>
#import <Bugly/Bugly.h>
#import <WechatOpenSDK/WXApi.h>
@import CoreTelephony;
#import "AFNetworkReachabilityManager.h"

@interface AppDelegate ()<UNUserNotificationCenterDelegate,WXApiDelegate>

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES] ;
    
    [Bugly startWithAppId:@"efb43ee81c"];
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:[SALoginVC new]];
    self.window.rootViewController = navigationController;
    [self.window makeKeyAndVisible];
    
    [self getDeviceInfo];
    [kUserDefault setObject:[self getUUIDString] forKey:kDeviceIdKey];
    
    BOOL weiXin = [WXApi registerApp:@"wx3bfb8a2426a7bcdf" universalLink:@"https://saas.fuyungroup.com/wholesale"];
    NSLog(@"%d",weiXin);
    
    // 设置全局键盘
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.enableAutoToolbar = NO;
    
    [UMConfigure initWithAppkey:@"60bdc8a3799cce47f9385685" channel:@"App Store"];
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    
    //百度ocr 身份证 和 银行卡
    [[AipOcrService shardService] authWithAK:@"k44tWstGHYG8Pf2s2hUBb9ye" andSK:@"XORfTQ2z78E97VxGLEvH3hogz60NYCaH"];
    
    //设置为自动采集页面
    [MobClick setAutoPageEnabled:YES];
    [UMCommonLogManager setUpUMCommonLogManager];
    
    //1.获取网络权限 根据权限进行人机交互
    if (__IPHONE_10_0) {
        [self networkStatus:application didFinishLaunchingWithOptions:launchOptions];
    }else {
        //2.2已经开启网络权限 监听网络状态
        [self addReachabilityManager:application didFinishLaunchingWithOptions:launchOptions];
    }
    
    return YES;
}

//初始化屏幕参数
- (void)getDeviceInfo {
    ScreenWidth = kScreenWidth;
    ScreenHeight = kScreenHeight;
    ScreenScale =  ScreenWidth / kBaseScreenWidth;
    SystemVersion = [UIDevice currentDevice].systemVersion.floatValue;
    
    if (KIsiPhoneX) {
        StatusHeight = 88.f;
        SafeFooterHeight = 34.f;
        SafeHeaderHeight = 44;
        DifferenceHeight = 24;
    }else{
        StatusHeight = 64.f;
        SafeFooterHeight = 0.f;
        SafeHeaderHeight = 20;
        DifferenceHeight = 0;
    }
}

-(NSString *)getUUIDString {
    
    SEL s = sel_registerName("advertisingIdentifier");
    SEL s2 = sel_registerName("UUIDString");
    
    ASIdentifierManager * manager = [ASIdentifierManager sharedManager];
    if([manager respondsToSelector:s])
    {
        IMP imp = [manager methodForSelector:s];
        id (*func)(id, SEL) = (void *)imp;
        id ii = func(manager, s);
        
        if([ii respondsToSelector:s2])
        {
            IMP imp1 = [ii methodForSelector:s2];
            id (* func1)(id,SEL) = (void *)imp1;
            NSString *uuid =  func1(ii,s2);
            if (uuid && ![uuid hasPrefix:@"00000000"]) {
                return uuid;
            }
        }
    }
    //没有获取到IDFA，用IDFV代替
    SEL s3 = sel_registerName("identifierForVendor");
    SEL s4 = sel_registerName("UUIDString");
    UIDevice *device = [UIDevice currentDevice];
    if ([device respondsToSelector:s3]) {
        IMP imp = [device methodForSelector:s3];
        id (*func)(id, SEL) = (void *)imp;
        id ii = func(device, s3);
        
        if([ii respondsToSelector:s4])
        {
            IMP imp1 = [ii methodForSelector:s4];
            id (* func1)(id,SEL) = (void *)imp1;
            return  func1(ii,s4);
        }
    }
    
    return [self uuid];
}

//获取手机Id
-(NSString *)uuid {
    CFUUIDRef puuid        = CFUUIDCreate(nil);
    CFStringRef uuidString = CFUUIDCreateString(nil, puuid);
    NSString *result       = (__bridge NSString *)CFStringCreateCopy(NULL, uuidString);
    CFRelease(puuid);
    CFRelease(uuidString);
    // 去掉"-"
    return [result stringByReplacingOccurrencesOfString:@"-" withString:@""];
}

#pragma mark - 程序进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application {
    //
    
}

#pragma mark - 程序进入前台
- (void)applicationDidBecomeActive:(UIApplication *)application {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"IntoTheFrontDesk" object:nil];
}

-(void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    
    NSMutableString *deviceTokenString = [NSMutableString string];
    const char *bytes = deviceToken.bytes;
    NSInteger iCount = deviceToken.length;
    for (NSInteger i = 0; i < iCount; i++) {
        [deviceTokenString appendFormat:@"%02x", bytes[i]&0x000000FF];
    }
    [kUserDefault setObject:deviceTokenString forKey:kDeviceTokenKey];
}

#pragma mark - 友盟推送
+(void)registerForRemoteNotificationsWithLaunchOptions:(NSDictionary*_Nullable)launchOptions Entity:(UMessageRegisterEntity*)entity completionHandler:(void(^_Nullable)(BOOL granted,NSError*__nullable error))completionHandler {
    [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity completionHandler:^(BOOL granted,NSError*_Nullable error){
        if(granted){
        }else{
        }
    }];
}

//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter*)center willPresentNotification:(UNNotification*)notification withCompletionHandler:(void(^)(UNNotificationPresentationOptions))completionHandler{
    NSDictionary* userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]){
        [UMessage setAutoAlert:NO];
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        if ([SAOverallSetting shareInstance].printerSetting.printerStatus == 2) {
            NSString *type = userInfo[@"type"];
            NSString *data = userInfo[@"data"];
            if (type.length > 0 && data.length > 0 ) {
                CloudPrint *print = [CloudPrint shareInstance];
                [print PrintWithType:type AndData:data];
            }
        }
    }else{
        //应用处于前台时的本地推送接受
        
    }
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter*)center didReceiveNotificationResponse:(UNNotificationResponse*)response withCompletionHandler:(void(^)(void))completionHandler{
    NSDictionary* userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]){
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
    }else{
        //应用处于后台时的本地推送接受
        
    }
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL * _Nonnull)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> * _Nonnull)options {
    return  [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity * _Nonnull)userActivity restorationHandler:(void (^ _Nonnull)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
    return [WXApi handleOpenUniversalLink:userActivity delegate:self];
}

#pragma mark WXApiDelegate 微信分享的相关回调
//onReq是微信终端向第三方程序发起请求，要求第三方程序响应。第三方程序响应完后必须调用sendRsp返回。在调用sendRsp返回时，会切回到微信终端程序界面。
- (void)onReq:(BaseReq *)req
{
    
}

- (void)onResp:(BaseResp *)resp
{
    switch (resp.errCode) {
        case WXSuccess:
        {
        }
            break;
        case WXErrCodeUserCancel:
            [[NSNotificationCenter defaultCenter] postNotificationName:@"WXUserCancelPay" object:nil];
            break;
        default:
        {
            
        }
            break;
    }
}

//监听网络
- (void)networkStatus:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //2.根据权限执行相应的交互
    CTCellularData *cellularData = [[CTCellularData alloc] init];
    
    /*
     此函数会在网络权限改变时再次调用
     */
    cellularData.cellularDataRestrictionDidUpdateNotifier = ^(CTCellularDataRestrictedState state) {
        switch (state) {
            case kCTCellularDataRestricted:
                
                NSLog(@"Restricted");
                //2.1权限关闭的情况下 再次请求网络数据会弹出设置网络提示
                
                break;
            case kCTCellularDataNotRestricted:
                
                NSLog(@"NotRestricted");
                //2.2已经开启网络权限 监听网络状态
                [self addReachabilityManager:application didFinishLaunchingWithOptions:launchOptions];
                break;
            case kCTCellularDataRestrictedStateUnknown:
                
                NSLog(@"Unknown");
                
                break;
                
            default:
                break;
        }
    };
}

- (void)addReachabilityManager:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    AFNetworkReachabilityManager *afNetworkReachabilityManager = [AFNetworkReachabilityManager sharedManager];
    
    
    [afNetworkReachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:{
                NSLog(@"网络不通：%@",@(status) );
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWiFi:{
                NSLog(@"网络通过WIFI连接：%@",@(status));
                
                [self getInfo_application:application didFinishLaunchingWithOptions:launchOptions];
                
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWWAN:{
                NSLog(@"网络通过无线连接：%@",@(status) );
                
                [self getInfo_application:application didFinishLaunchingWithOptions:launchOptions];
                
                break;
            }
            default:
                break;
        }
    }];
    
    [afNetworkReachabilityManager startMonitoring];  //开启网络监视器；
}

//把以前写在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions里面的一些初始化操作放在该方法
- (void)getInfo_application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //    [self.updateBusiness  checkUpdateWithBothApi];//检查app更新
    
    //发送通知给APP首屏页面，让其有网络时重新请求
    [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil];
}

@end

